import 'dart:convert';
import 'dart:developer';

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:get_storage/get_storage.dart';
import 'package:jxchmz/%E9%A6%96%E9%A1%B5/Home.dart';
import 'package:jxchmz/API/LoginApi.dart';
import 'package:jxchmz/BottomTabbar.dart';
import 'package:jxchmz/Getx%E5%B7%A5%E5%85%B7/GetxTools.dart';
import 'package:jxchmz/Getx%E5%B7%A5%E5%85%B7/KSProgressDialog.dart';
import 'package:package_info/package_info.dart';
import 'package:roundcheckbox/roundcheckbox.dart';
import 'package:shared_preferences/shared_preferences.dart';

class Login extends StatefulWidget {
  @override
  _LoginState createState() => new _LoginState();
}

class _LoginState extends State<Login> {
  ///  点击返回的次数
  int BackNum = 0;
  int last = 0;

  /// 响应空白处的焦点的Node
  FocusNode blankNode = FocusNode();

//控制密码显示隐藏
  bool passwordVisible = false;

//是否记住密码
  bool check = false;

//手机号
  var _Phone = "";

  /**
   * 密码
   */
  var _Password = "";
  PackageInfo _packageInfo = PackageInfo(
    appName: 'Unknown',
    packageName: 'Unknown',
    version: 'Unknown',
    buildNumber: 'Unknown',
  );

  //当前使用语言
  var Langage;

  //语言默认
  var LangageDefual = "";

  //本地缓存初始化
  //输入框控制器
  TextEditingController _PasswordController = TextEditingController();
  TextEditingController _PhoneController = TextEditingController();

  //get网络请求类
  LoginApi loginApi = new LoginApi();

  //读取本地缓存，查看是否记住密码
  GetStorage storage = GetStorage();

  // TODO: add state variables and methods
  @override
  Widget build(BuildContext context) {
    // TODO: add widget build method
    return Scaffold(
        body: SingleChildScrollView(
      child: WillPopScope(
        onWillPop: () async {
          //计算两次时间间隔
          int now = DateTime.now().millisecondsSinceEpoch;
          if (now - last > 8000) {
            last = DateTime.now().millisecondsSinceEpoch;
            Get.snackbar("提示", "再次点击返回退出应用");
            return Future.value(false);
          } else {
            return Future.value(true);
          }
        },
        child: Column(
          children: [
            Stack(
              alignment: Alignment.topCenter,
              children: [
                Container(
                  height: 250,
                  width: MediaQuery.of(context).size.width,
                  decoration: BoxDecoration(
                    image: DecorationImage(
                      image: AssetImage("Image/LoginBack.png"),
                      fit: BoxFit.fill,
                    ),
                  ),
                ),
                Column(
                  children: [
                    Container(
                      margin: EdgeInsets.only(top: 50),
                      height: 80,
                      width: 80,
                      child: Card(
                        // shape: RoundedRectangleBorder(
                        //     borderRadius:
                        //     BorderRadiusDirectional.circular(
                        //         20)),
                        clipBehavior: Clip.antiAlias,
                        child: Image.asset(
                          "Image/LOGO.png",
                          width: double.maxFinite,
                        ),
                      ),
                    ),
                    Container(
                      height: 5,
                    ),
                    Container(
                      child: Text(
                        "Invoicingandinventorymanagement".tr,
                        style: TextStyle(color: Colors.white, fontSize: 20, fontWeight: FontWeight.w600),
                      ),
                    ),
                  ],
                ),
                //下拉选择语言
                Positioned(
                  top: 50,
                  right: 10,
                  child: Container(
                      // width: 120,
                      child: PopupMenuButton<String>(
                    child: Row(
                      children: [
                        Text(
                          '$LangageDefual',
                          style: TextStyle(color: Colors.white),
                        ),
                        Icon(
                          Icons.arrow_drop_down,
                          color: Colors.white,
                        )
                      ],
                    ),
                    itemBuilder: (context) {
                      return <PopupMenuEntry<String>>[
                        PopupMenuItem<String>(
                          value: 'zh-CN',
                          child: Text('简体中文'),
                        ),
                        PopupMenuItem<String>(
                          value: 'zh-TW',
                          child: Text('繁体中文'),
                        ),
                        PopupMenuItem<String>(
                          value: 'en-US',
                          child: Text('英语'),
                        ),
                      ];
                    },
                    onSelected: (value) async {
                      print('$value');
                      List CodeList = [];
                      CodeList = value.split("-");
                      print("语言代码数组$CodeList");
                      Get.updateLocale(Locale(CodeList[0], CodeList[1]));
                      var LangageName;
                      //保存设置的语言
                      if (CodeList[1] == "CN") {
                        //简体中文
                        LangageName = "简体中文";
                      }
                      if (CodeList[1] == "TW") {
                        //繁体中文
                        LangageName = "繁体中文";
                      }
                      if (CodeList[1] == "US") {
                        //英文
                        LangageName = "英文";
                      }
                      var data = {"LangageName": LangageName, "LangageCode": value};
                      await storage.write("Langage", json.encode(data));
                      LangageDefual = LangageName;
                      setState(() {
                      });
                    },
                  )
                      // DropdownButtonFormField(
                      //   value: _value,
                      //   items: [
                      //     DropdownMenuItem(
                      //       child: Text('简体中文'),
                      //       value: 'zh-CN',
                      //     ),
                      //     DropdownMenuItem(child: Text('繁体中文'), value: 'zh-TW'),
                      //     DropdownMenuItem(child: Text('英语'), value: 'en-US'),
                      //   ],
                      //   onChanged: (String? value) {
                      //     setState(() {
                      //       _value = value!;
                      //       List CodeList = [];
                      //       CodeList = _value.split("-");
                      //       print("语言代码数组$CodeList");
                      //       Get.updateLocale(Locale(CodeList[0], CodeList[1]));
                      //     });
                      //   },
                      //   style: TextStyle(color: Colors.white),
                      //   decoration: InputDecoration(
                      //     border: OutlineInputBorder(
                      //         borderSide: BorderSide.none),
                      //     //去除下边框
                      //   ),
                      //   iconEnabledColor: Colors.white,
                      //   iconDisabledColor: Colors.white,
                      // ),
                      ),
                )
              ],
            ),
            // 账号
            Container(
                margin: EdgeInsets.only(left: 30, top: 50, right: 30),
                child: Row(
                  children: [
                    Container(
                      child: Icon(
                        Icons.phone_android,
                        // color: Color(0xff1bccb9),
                        color: Color(0xff1bccb9),
                        size: 30,
                      ),
                    ),
                    Container(
                      width: 15,
                    ),
                    Expanded(
                      child: TextField(
                        cursorColor: Color(0xff1bccb9),
                        controller: _PhoneController,
                        decoration: InputDecoration(
                          hintText: "Pleaseentertheaccountnumber".tr,
                          hintStyle: TextStyle(fontSize: 13, color: Colors.black26),
                          enabledBorder: UnderlineInputBorder(
                              borderSide: BorderSide(
                            width: 0.5,
                            color: Colors.black26,
                          )),
                          focusedBorder: UnderlineInputBorder(
                            borderSide: BorderSide(
                              color: Color(0xff1bccb9),
                            ),
                          ),
                        ),
                      ),
                    )
                  ],
                )),
            // 密码
            Container(
                margin: EdgeInsets.only(left: 30, top: 30, right: 30),
                child: Row(
                  children: [
                    Container(
                      child: Icon(
                        Icons.https,
                        color: Color(0xff1bccb9),
                        size: 30,
                      ),
                    ),
                    Container(
                      width: 15,
                    ),
                    Expanded(
                      child: TextField(
                        obscureText: passwordVisible,
                        controller: _PasswordController,
                        decoration: InputDecoration(
                          hintText: "Pleaseenterapassword".tr,
                          hintStyle: TextStyle(fontSize: 13, color: Colors.black26),
                          suffixIcon: IconButton(
                            icon: Icon(
                              passwordVisible ? Icons.visibility_off : Icons.visibility,
                              color: passwordVisible ? Colors.black26 : Color(0xff1bccb9),
                            ),
                            onPressed: () {
                              setState(() {
                                passwordVisible = !passwordVisible;
                              });
                            },
                          ),
                          enabledBorder: UnderlineInputBorder(borderSide: BorderSide(width: 0.5, color: Colors.black26)),
                          focusedBorder: UnderlineInputBorder(
                            borderSide: BorderSide(
                              color: Color(0xff1bccb9),
                            ),
                          ),
                        ),
                      ),
                    )
                  ],
                )),
            RememberPassword(context),
            Container(
              margin: EdgeInsets.fromLTRB(100, 50, 100, 0),
              decoration: BoxDecoration(borderRadius: BorderRadius.circular(25)),
              child: RaisedButton(
                shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(25)),
                color: Color(0xff1bccb9),
                // 设为透明色
                elevation: 0,
                // 正常时阴影隐藏
                highlightElevation: 0,
                // 点击时阴影隐藏
                onPressed: () {
                  if (_PhoneController.text.isEmpty || _PasswordController.text.isEmpty) {
                    new GetxTools().WaringToast("Pleaseenteryouraccountnumberorpassword".tr);
                    return;
                  }

                  StartLogin();
                },
                child: Container(
                  alignment: Alignment.center,
                  child: Text(
                    'login'.tr,
                    style: TextStyle(color: Colors.white, fontSize: 15),
                  ),
                ),
              ),
            ),
            Container(
              height: 15,
            ),
            Container(
              child: Text(
                "V${_packageInfo.version}",
                style: TextStyle(color: Colors.black),
              ),
            ),
            // MaterialButton(
            //   child: Text("切换语言"),
            //   onPressed: (){
            //     print("语言代码:${Get.deviceLocale}");
            //     Get.updateLocale(Locale("en", "US"));
            //   },
            //   color: Colors.blue,
            // )
          ],
        ),
      ),
    ));
  }

//页面加载完成时
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    Future.delayed(Duration.zero, () async {
      SharedPreferencesIsCheck();
      final PackageInfo info = await PackageInfo.fromPlatform();
      _packageInfo = info;

    });
  }

  ///页面卸载
  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
  }

  ///当 State 被暂时从视图树中移除时，会调用这个方法，同时页面切换时，也会调用。
  @override
  void deactivate() {
    // TODO: implement dispose
    super.deactivate();
  }

  ///在 initState() 之后调用，当 State 对象的依赖关系发生变化时，该方法被调用，初始化时也会调用。
  @override
  void didChangeDependencies() {
    // TODO: implement didChangeDependencies
    super.didChangeDependencies();
  }

  //忘记密码和记住密码
  Widget RememberPassword(context) {
    return Container(
      padding: EdgeInsets.only(left: 20, right: 20),
      margin: EdgeInsets.only(top: 10),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Row(
            children: [
              RoundCheckBox(
                  size: 15,
                  checkedWidget: const Icon(
                    Icons.check,
                    color: Colors.white,
                    size: 10,
                  ),
                  checkedColor: Color(0xff1bccb9),
                  uncheckedColor: Color(0x003C78FF),
                  border: Border.all(color: getCheckBoxBorderColor(), width: 1),
                  isChecked: check,
                  onTap: (selected) {
                    check = selected!;
                    setState(() {});
                  }),
              Container(
                margin: EdgeInsets.only(left: 5),
                child: Text(
                  "Rememberthepassword".tr,
                  style: TextStyle(fontSize: 12, color: Colors.black38),
                ),
              )
            ],
          ),
          //忘记密码
          // GestureDetector(
          //   child: Container(
          //       child: Text("忘记密码?",
          //           style: TextStyle(color: Color(0xff1bccb9), fontSize: 12))),
          //   onTap: () {},
          // ),
        ],
      ),
    );
  }

  //复选框选中事件
  getCheckBoxBorderColor() {
    if (check) {
      return Color(0xff1bccb9);
    } else {
      return const Color(0xFFD1D1D1);
    }
  }

  //检测本地缓存是否记住密码/
  Future<void> SharedPreferencesIsCheck() async {
    Future.delayed(Duration(milliseconds: 500), () async {
      bool? SharedIsCheck = await storage.read("Check");
      String? SharedPhone = await storage.read("Phone");
      String? SharedPassword = await storage.read("Password");
      print("账号$SharedIsCheck");
      if (SharedIsCheck == true) {
        check = true;
        print("账号$SharedPhone");
        print("密码$SharedPassword");
      } else {
        check = false;
        SharedPhone = "";
        SharedPassword = "";
      }
      _PasswordController = new TextEditingController(text: SharedPassword);
      _PhoneController = new TextEditingController(text: SharedPhone);
      setState(() {
      });
      //获取系统语言
      String LangStr = Get.deviceLocale.toString();
      //获取本地保存的语言种类
      var data;
      var LangageName;
      var LangageCode;
      print("本地语言数据:${await storage.read("Langage")}");
      if (await storage.read("Langage") == null) {
        List list = LangStr.split("_");
        if (list[1] == "US") {
          LangageName = "英文";
        }
        if (list[1] == "CN") {
          LangageName = "简体中文";
        }
        if (list[1] == "TW") {
          LangageName = "繁体中文";
        }
        LangageCode = list.join("-");
        data = {"LangageName": LangageName, "LangageCode": LangageCode};
        //没有设置过语言，自动设置系统的默认语言
        await storage.write("Langage", json.encode(data));
      }
      var LangageData = await storage.read("Langage");
      Langage = json.decode(LangageData);
      LangageDefual = Langage['LangageName'];
      List CodeList = [];
      CodeList = Langage['LangageCode'].split("-");
      Get.updateLocale(Locale(CodeList[0], CodeList[1]));
      print("本地语言:${await storage.read("Langage")}");
      setState(() {});
    });
  }

  // 登录
  Future<void> StartLogin() async {
    var ResponseData;
    // 本地保存个人信息
    // GetStorage storage = GetStorage();

    var Data = {"username": _PhoneController.text, "password": _PasswordController.text};
    KSProgressDialog().LoadingToast("Loggingin".tr, context);
    ResponseData = await loginApi.Login(Data);
    KSProgressDialog().CloseLoading();
    if (ResponseData['code'] == 200) {
      //登陆成功后,本地保存是否记住密码
      await storage.write('Check', check);
      await storage.write('Phone', _PhoneController.text);
      await storage.write('Password', _PasswordController.text);
      await storage.write('Token', ResponseData['token']);
      new GetxTools().SuccessToast("Loginsuccessful".tr);
      Get.off(() => BottomTabbar());
    } else {
      new GetxTools().ErrorToast("Loginfailed".tr);
      // ShowToast().MyToast(ResponseData['message']);
    }
  }
}
